import Vue from 'vue'
import VueRouter from 'vue-router'
import { Message } from "element-ui";

Vue.use(VueRouter)

const routes = [
  {
    path: "/",			// 匹配用户访问的请求
    redirect: "/index"		// 将用户的请求重新定向到另一个请求
  },
  {
    path: '/index',
    name: 'index',
    component: () => import('../views/index.vue'),
    redirect:'/index/cart_info2',
    children: [
      {
        path: 'cart_info1',
        name: 'cart_info1',
        component: () => import('../views/cart_info1.vue')
      },
      {
        path: 'cart_info2',
        name: 'cart_info2',
        component: () => import('../views/cart_info2.vue')
      },
      {
        path: 'cart_info3',
        name: 'cart_info3',
        component: () => import('../views/cart_info3.vue')
      },
      {
        path: 'cart_info4',
        name: 'cart_info4',
        component: () => import('../views/cart_info4.vue')
      },
      {
        path: 'cart_info5',
        name: 'cart_info5',
        component: () => import('../views/cart_info5.vue')
      },

    ]
  },
  {
    path: '/search_view',
    name: 'search_view',
    component: () => import('../views/search_view.vue')
  },
  {
    path: '/mannge',
    name: 'mannge',
    component: () => import('../views/mannge.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/register.vue')
  },
]
const router = new VueRouter({
  mode: "history",
  routes
})

//添加以下代码
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to,form,next)=>{
  if(to.path=='/login'){
    sessionStorage.removeItem("user");
  }
  let user = JSON.parse(sessionStorage.getItem("user"));
  if(!user&&to.path!='/login'&& to.path!='/register'){
    Message({
      message: '用户暂未登录',
      type: 'warning'
    });
    next({path:'/login'})
  }else{
    next();
  }
})

export default router